package com.edmendst.xmall.controller;

import com.edmendst.xmall.dto.DeliveryInfo;
import com.edmendst.xmall.dto.LoginRequest;
import com.edmendst.xmall.dto.UserInFo;
import com.edmendst.xmall.dto.UserTypeTranslate;
import com.edmendst.xmall.pojo.User;
import com.edmendst.xmall.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @author mjz
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;


    // 注册新用户
    @PostMapping
    public ResponseEntity<String> registerUser(@Valid @RequestBody User user) {
        return ResponseEntity.ok(userService.register(user));
    }

    //登录
    @PostMapping("/session")
    public String login(@RequestBody LoginRequest loginRequest, HttpServletResponse response) {
        String token = userService.login(loginRequest);

        if (token != null) {
            response.setHeader("Authorization", token);
        } else {
            System.out.println("登录失败");
            return "登录失败";
        }
        System.out.println("登录成功");
        return token;

    }

//    //注销
//    public String logout(String token);
@PostMapping("/logout")
public ResponseEntity<String> logout(HttpServletRequest request) {
    // 从请求头获取Authorization
    String header = request.getHeader("Authorization");
    if (header == null || !header.startsWith("Bearer ")) {
        return ResponseEntity.badRequest().body("缺少有效的Token");
    }

    String token = header.substring(7);
    return ResponseEntity.ok(userService.logout(token));
}

    // 获取当前用户信息
    @GetMapping
    public UserInFo getCurrentUser() {


        // 通过SecurityContext获取已认证用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        System.out.println("获取当前用户信息");
        return userService.selectUserByUserName(username);
    }

    // 更新用户昵称
    @PutMapping("/nickname")
    public int updateUserNickname(@RequestBody Map<String, String> requestBody) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        String userNickname = requestBody.get("userNickname");
        return userService.updateUserNickname(userNickname, username);
    }


    // 更新用户签名
    @PutMapping("/signature")
    public int updateUserSignature(@RequestBody Map<String, String> requestBody) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        String userSignature = requestBody.get("userSignature");
        return userService.updateUserSignature(userSignature, username);
    }


    // 更新用户密码
    @PutMapping("/password")
    public int updateUserPassword(@RequestBody Map<String, String> requestBody) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        String userPassword1 = requestBody.get("userPassword1");
        String userPassword2 = requestBody.get("userPassword2");
        return userService.updateUserPassword(userPassword1, userPassword2, username);
    }


    //// 更新用户头像
    @PutMapping("/image")
    public String updateUserImage(@RequestParam MultipartFile userImage) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();

        // 检查文件是否为空
        if (userImage == null || userImage.isEmpty()) {
            return "文件为空，无法上传！";
        }
        int i = userService.updateUserImage(userImage, username);
        if (i == 1) {
            return "上传成功";
        }
        return "上传失败";
    }

    /**
     * @param userType
     * 'buyer','seller','both'
     * @return
     */
    // 更新用户类型
    @PutMapping("/{userType}")
    public String updateUserType(@PathVariable String userType) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        UserTypeTranslate userTypeTranslate = new UserTypeTranslate();
        userTypeTranslate.setUserName(username);
        userTypeTranslate.setUserType(userType);
        return userService.updateUserType(userTypeTranslate);
    }

    @PostMapping("/delivery")
    public int addDeliveryInfo(@RequestBody DeliveryInfo deliveryInfo) throws JsonProcessingException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        return userService.addDeliveryInfo(username,deliveryInfo);
    }

    @PutMapping("/delivery/{addressId}")
    public int updateDefaultAddress(@PathVariable Long addressId) throws JsonProcessingException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
      return userService.updateDefaultAddress(username,addressId);
    }

    @GetMapping("/delivery")
    public List<DeliveryInfo> getDeliveryInfo() throws JsonProcessingException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        return userService.getAllDeliveryInfoList(username);
    }

}